package com.project.rfidtodb.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    public static <T> T getBean(Class<T> clazz) {
        if (applicationContext == null) {
            throw new IllegalStateException("Spring application context is not initialized");
        }

        // 使用其他方式判断上下文状态
        try {
            return applicationContext.getBean(clazz);
        } catch (Exception e) {
            throw new IllegalStateException("Failed to get bean from Spring context", e);
        }
    }
}
